package com.gitee.cirnochat.login.aop;

import com.gitee.cirnochat.common.utils.RequestUtils;
import com.gitee.cirnochat.login.annotation.TrackLogin;
import com.gitee.cirnochat.login.model.dto.DeviceInfo;
import com.gitee.cirnochat.login.model.enums.DeviceType;
import com.gitee.cirnochat.login.service.LoginDeviceService;
import com.gitee.cirnochat.login.service.LoginHistoryService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class UserLoginInterceptor {
    private final LoginDeviceService loginDeviceService;
    private final LoginHistoryService loginHistoryService;
    private final HttpServletRequest request;

    /**
     * 正常登录时记录设备和登录历史
     */
    @AfterReturning("@annotation(trackLogin)")
    public void trackLoginSuccess(JoinPoint joinPoint, TrackLogin trackLogin) {
        Long userId = RequestUtils.getUserId(request);
        String userAgentStr = RequestUtils.getUserAgent(request);
        String ipAddress = RequestUtils.getIp(request);
        String deviceId = RequestUtils.getDeviceId(request);
        String deviceName = RequestUtils.getDeviceName(request);
        DeviceType deviceType = DeviceType.fromValue(Integer.valueOf(RequestUtils.getDeviceType(request)));

        loginDeviceService.saveOrUpdateLoginDeviceAsync(deviceId, ipAddress, new DeviceInfo(deviceName,deviceType), userId);
        loginHistoryService.saveLoginHistoryAsync(deviceId,ipAddress,new DeviceInfo(deviceName,deviceType), userAgentStr,1 , userId);
    }

    /**
     * 登录失败（方法抛异常时）记录登录历史但不记录设备
     */
    @AfterThrowing(value = "@annotation(trackLogin)", throwing = "ex")
    public void trackLoginFail(JoinPoint joinPoint, TrackLogin trackLogin, Throwable ex) {
        Long userId = RequestUtils.getUserId(request);
        String userAgentStr = RequestUtils.getUserAgent(request);
        String ipAddress = RequestUtils.getIp(request);
        String deviceId = RequestUtils.getDeviceId(request);
        String deviceName = RequestUtils.getDeviceName(request);
        DeviceType deviceType = DeviceType.fromValue(Integer.valueOf(RequestUtils.getDeviceType(request)));

        if (userId != null) {
            // 登录失败只记录历史，不记录设备
            loginHistoryService.saveLoginHistoryAsync(deviceId,ipAddress, new DeviceInfo(deviceName,deviceType), userAgentStr,0, userId);
        }
    }
}
